package cn.edu.njust.controller;

import cn.edu.njust.core.UserContext;
import cn.edu.njust.pojo.bo.RestResult;
import cn.edu.njust.pojo.bo.Token;
import cn.edu.njust.pojo.bo.VerifyImage;
import cn.edu.njust.pojo.dto.LoginDTO;
import cn.edu.njust.pojo.dto.UserRegisterDTO;
import cn.edu.njust.pojo.po.User;
import cn.edu.njust.service.SystemService;
import cn.edu.njust.util.CheckCodeUtil;
import cn.edu.njust.util.SystemUtils;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 基础通用功能接口
 */

@Tag(name = "基础通用功能接口")
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/common")
public class CommonController {

    private static final String CHECK_CODE = "checkCode";

    private final SystemService systemService;

    /**
     * 登录功能
     *
     * @param login 登录信息
     * @since 2.0.0
     */

    @Operation(summary = "登录功能", description = "登录功能")
    @PostMapping("/login")
    public Token login(@RequestBody LoginDTO login, HttpServletRequest request) {

        String checkCode = (String) request.getSession().getAttribute(CHECK_CODE);
        SystemUtils.checkCodeIsRight(checkCode, login.getCheckCode());

        User loginUser = new User();
        loginUser.setCode(login.getCode());
        loginUser.setPassword(login.getPassword());

        User user = systemService.login(loginUser);
        return BeanUtil.copyProperties(user, Token.class);
    }

    /**
     * 退出登录功能
     */
    @Operation(summary = "退出登录功能", description = "退出登录功能")
    @PostMapping("/loginOut")
    public RestResult<Void> loginOut() {
        UserContext.removeCurrentUser();
        return RestResult.success();
    }

    /**
     * 获取验证码
     *
     * @since 2.0.0
     */
    @Operation(summary = "获取验证码", description = "获取验证码")
    @GetMapping("/getCheckCode")
    public RestResult<String> getCheckCode(HttpServletRequest request) {
        VerifyImage verifyImage = CheckCodeUtil.outputVerifyImage(120, 50, 4);
        request.getSession().setAttribute(CHECK_CODE, verifyImage.getCode());
        return RestResult.success(verifyImage.getImage());
    }

    /**
     * 用户注册
     *
     * @param userRegister 注册信息
     * @since 2.0.0
     */
    @Operation(summary = "用户注册", description = "用户注册")
    @PostMapping("/register")
    public RestResult<Object> register(@RequestBody UserRegisterDTO userRegister, HttpServletRequest request) {

        String checkCode = (String) request.getSession().getAttribute(CHECK_CODE);
        SystemUtils.checkCodeIsRight(checkCode, userRegister.getCheckCode());

        systemService.addUser(BeanUtil.copyProperties(userRegister, User.class));

        return RestResult.success();
    }
}
